package com.shouxue.dragrvdemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;

import java.util.ArrayList;
import java.util.List;

/**
 * @author COT, uidq5175
 * Time: 2023-2-6 14:35
 * Description: 动画相关工具类
 * <p>
 * Copyright (c) 2023 Desaysv All rights reserved.
 */
public class AnimationUtil {

    /**
     * 左右旋转晃动动画-以中心点为旋转轴
     * <p>
     * 那么CycleInterpolator是干嘛用的？？
     * Api demo里有它的用法，是个摇头效果！
     * todo 有锯齿需要在代码中添加抗锯齿
     *
     * @param counts 1秒钟晃动多少下
     * @param degree 旋转角度
     * @return Animation
     */
    public static Animation rotateShakeAnimation(int counts, int degree) {
        Animation rotateAnimation = new RotateAnimation(-degree * 10, degree,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setRepeatCount(-1);
        rotateAnimation.setDuration(1000 / counts);
        return rotateAnimation;
    }

    /**
     * 左右旋转晃动动画-以中心点为旋转轴-属性动画完成
     * todo 有锯齿需要在代码中添加抗锯齿
     *
     * @param view   需要执行动画的view
     * @param counts 频率，1秒几次
     * @param degree 偏转幅度
     */
    public static AnimatorSet rotateShakeAnimation(View view, int counts, float degree) {

        ObjectAnimator rotation;
        rotation = ObjectAnimator.ofFloat(view, "rotation", -degree / 2F, degree / 2F, -degree / 2F);
        rotation.setRepeatCount(-1);

        //使用list将需要执行的动画临时存起来
        List<Animator> tempAnimator = new ArrayList<>();

        //添加轴旋转动画
        tempAnimator.add(rotation);

        AnimatorSet animatorSet = new AnimatorSet();
        //一起执行动画
        animatorSet.playTogether(tempAnimator);

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                //动画执行完毕释放锁
                animatorSet.removeAllListeners();
                animatorSet.cancel();
            }
        });

        animatorSet.setInterpolator(new LinearInterpolator());
        //添加执行时间
        animatorSet.setDuration(1000 / counts);
        //start方法一定要放在最后
        return animatorSet;
    }

    /**
     * 左右抖动动画-以Y轴为中心
     * <p>
     * 那么CycleInterpolator是干嘛用的？？
     * Api demo里有它的用法，是个摇头效果！
     *
     * @param counts 1秒钟抖动多少下
     * @param offset 偏移量
     * @return Animation
     */
    public static Animation translateShakeAnimation(int counts, int offset) {
        Animation translateAnimation = new TranslateAnimation(0, offset, 0, 0);
        translateAnimation.setRepeatCount(-1);
        translateAnimation.setDuration(1000);
        return translateAnimation;
    }
}
